<template>
  <div>
    <uploadExcel :before-upload="beforUploadFn" :on-success="onSuccessFn" />
  </div>
</template>

<script>
import { uploadExcelApi } from '@/api/uploadExcel'
export default {
  methods: {
    beforUploadFn(rawFile) {
      // //console.log('上传前', rawFile)
      if (rawFile.size > 2 * 1024 * 1024) {
        this.$message.error('文件大于2M')
      } else {
        return true
      }
    },
    async onSuccessFn(excelData) {
      // console.log('数据', excelData)

      const data = excelData.results.map(item => {
        return this.transform({ ...item })
      })
      // //console.log('处理后', data)
      await uploadExcelApi(data)
      this.$router.back()
    },
    transform(val) {
      const dictionaries = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const newObj = {}
      for (const key in val) {
        const newKey = dictionaries[key]
        const value = val[key]
        if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          newObj[newKey] = new Date(this.formatDateExcel(value))
        } else {
          newObj[newKey] = value
        }
      }
      return newObj
    },
    formatDateExcel(num, format = '-') {
      num = Number(num)	// 强制类型转化，以防传来的值是字符串
      let millisecond = 0	// 转化后的毫秒数
      if (num > 60) {
        millisecond = (num - 25569) * 60 * 60 * 24 * 1000
      } else {
        millisecond = (num - 25568) * 60 * 60 * 24 * 1000
      }
      const date = new Date(millisecond)	// 根据转化后的毫秒数获取对应的时间
      const yy = date.getFullYear()
      const mm = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      const dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      return yy + format + mm + format + dd	// 返回格式化后的日期
    }
  }
}
</script>

<style>

</style>
